标签:
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 24134 | Accepted: 9177 |
Description
Input
Output
Sample Input
5 3 7 3 8 10 3 6 8 1 1 3 1 10 11 1
Sample Output
6
差分约束系统模板题;转换为最短路来求解,关键是建图;
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<queue> #include<algorithm> #include<iostream> #include<vector> void spaf(int n,int ans); using namespace std; const int N=1e9; int d[30005*5]; bool flag[30005*5]; void add(int x,int y,int z,int co); typedef struct pp { int x; int y; int cost; int pre; }ss;ss aa[30005*5]; int id[30005*5]; int main(void) { int i,j,k,p,q;int z; int maxx=0; while(scanf("%d",&k)!=EOF) {int ans=0; fill(id,id+30005*5,-1); while(k--) { scanf("%d %d %d",&p,&q,&z); if(maxx<p)maxx=p; if(maxx<q)maxx=q; add(p-1,q,ans++,-z); } for(i=1; i<=maxx; i++) { add(i-1,i,ans++,0); add(i,i-1,ans++,1); }spaf(0,maxx);printf("%d\n",-d[maxx]); } } void spaf(int n,int ans) { fill(d,d+30005*5,N); d[n]=0; queue<int>que;int i; memset(flag,0,sizeof(flag)); flag[n]=true; que.push(n); while(!que.empty()) { int c=que.front(); que.pop(); flag[c]=false; int x=id[c]; while(x!=-1) { int uu=aa[x].y; if(d[uu]>d[c]+aa[x].cost) {d[uu]=d[c]+aa[x].cost; if(!flag[uu]) {que.push(uu); flag[uu]=true; } } x=aa[x].pre; } } } void add(int x,int y,int z,int co) { aa[z].x=x; aa[z].y=y; aa[z].cost=co; aa[z].pre=id[x]; id[x]=z; }
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 13511 | Accepted: 5756 |
Description
Input
Output
Sample Input
4 3 6 2 4 0 2 4 7
Sample Output
4
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<queue> 5 #include<algorithm> 6 #include<iostream> 7 #include<vector> 8 void spaf(int n,int ans); 9 using namespace std; 10 const int N=1e9; 11 int d[30005]; 12 bool flag[30005]; 13 void add(int x,int y,int z,int co); 14 typedef struct pp 15 { 16 int x; 17 int y; 18 int cost; 19 int pre; 20 }ss;ss aa[30005]; 21 int id[30005]; 22 int main(void) { 23 int i,j,k,p,q; 24 int maxx=0; 25 while(scanf("%d",&k)!=EOF) {int ans=0; 26 fill(id,id+30005,-1); 27 while(k--) { 28 scanf("%d %d",&p,&q); 29 p++; 30 q++; 31 if(maxx<p)maxx=p; 32 if(maxx<q)maxx=q; 33 add(p-1,q,ans++,-2); 34 } 35 for(i=1; i<=maxx; i++) { 36 add(i-1,i,ans++,0); 37 add(i,i-1,ans++,1); 38 }spaf(0,maxx);printf("%d\n",-d[maxx]); 39 } 40 } 41 42 void spaf(int n,int ans) { 43 fill(d,d+30005,N); 44 d[n]=0; 45 queue<int>que;int i; 46 memset(flag,0,sizeof(flag)); 47 flag[n]=true; 48 que.push(n); 49 while(!que.empty()) { 50 int c=que.front(); 51 que.pop(); 52 flag[c]=false; 53 int x=id[c]; 54 while(x!=-1) 55 { 56 int uu=aa[x].y; 57 if(d[uu]>d[c]+aa[x].cost) 58 {d[uu]=d[c]+aa[x].cost; 59 if(!flag[uu]) 60 {que.push(uu); 61 flag[uu]=true; 62 } 63 } 64 x=aa[x].pre; 65 } 66 67 } 68 } 69 void add(int x,int y,int z,int co) 70 { 71 aa[z].x=x; 72 aa[z].y=y; 73 aa[z].cost=co; 74 aa[z].pre=id[x]; 75 id[x]=z; 76 }
标签:
原文地址:http://www.cnblogs.com/zzuli2sjy/p/5293110.html