It is vitally important to have all the cities connected by highways in a war. If a city is conquered by the enemy, all the highways from/toward that city will be closed. To keep the rest of the cities connected, we must repair some highways with the minimum cost. On the other hand, if losing a city will cost us too much to rebuild the connection, we must pay more attention to that city.
Given the map of cities which have all the destroyed and remaining highways marked, you are supposed to point out the city to which we must pay the most attention.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 2 numbers N (≤500), and M, which are the total number of cities, and the number of highways, respectively. Then M lines follow, each describes a highway by 4 integers: City1 City2 Cost Status where City1 and City2 are the numbers of the cities the highway connects (the cities are numbered from 1 to N), Cost is the effort taken to repair that highway if necessary, and Status is either 0, meaning that highway is destroyed, or 1, meaning that highway is in use.
Note: It is guaranteed that the whole country was connected before the
war.
Output Specification:
For each test case, just print in a line the city we must protest the most, that is, it will take us the maximum effort to rebuild the connection if that city is conquered by the enemy.
In case there is more than one city to be printed, output them in increasing order of the city numbers, separated by one space, but no extra space at the end of the line. In case there is no need to repair any highway at all, simply output 0.
Sample Input 1:
4 5
1 2 1 1
1 3 1 1
2 3 1 0
2 4 1 1
3 4 1 0
Sample Output 1:
1 2
Sample Input 2:
4 5
1 2 1 1
1 3 1 1
2 3 1 0
2 4 1 1
3 4 2 1
Sample Output 2:
0
#include
using namespace std;
struct s{
int a,b,c;
};
s s1[501*501],s2[501*501];
int n,m,p=0,q=0,fa[501],ans[501];
int ff(int a)
{
if(a==fa[a])return a;
else return fa[a]=ff(fa[a]);
}
bool c(s a,s b)
{
return a.c<b.c;
}
int main()
{
for(int i=1;i<=500;i++)fa[i]=i;
cin>>n>>m;
for(int i=0;i<m;i++)
{
int a,b,c,d;
scanf("%d%d%d%d",&a,&b,&c,&d);
if(d==0)
{
s2[q].a=a;
s2[q].b=b;
s2[q++].c=c;
}
else
{
s1[p].a=a;
s1[p].b=b;
s1[p++].c=0;
}
}
// sort(s1,s1+p,c);
sort(s2,s2+q,c);
int mmax=0;vector<int>v;
for(int i=1;i<=n;i++)
{
for(int k=1;k<=500;k++)fa[k]=k;
int cost=0,num=0;
for(int j=0;j<p;j++)
{
if(s1[j].a==i||s1[j].b==i)continue;
if(ff(s1[j].a)!=ff(s1[j].b))
{
num++;
fa[ff(s1[j].a)]=ff(s1[j].b);
}
}
for(int j=0;j<q;j++)
{
if(s2[j].a==i||s2[j].b==i)continue;
if(ff(s2[j].a)!=ff(s2[j].b))
{
num++;
fa[ff(s2[j].a)]=ff(s2[j].b);
cost+=s2[j].c;
}
}
if(num<n-2)cost=1e9;
if(cost==mmax)
{
v.push_back(i);
}
else if(cost>mmax)
{
mmax=cost;
v.clear();
v.push_back(i);
}
}
if(mmax==0)
{
cout<<0;return 0;
}
// sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
{
if(i==0)printf("%d",v[i]);
else printf(" %d",v[i]);
}
return 0;
}